//二叉搜索树
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public  TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;
    //插入一个结点
    public void insert(int key){
        if(root==null){
            root=new TreeNode(key);
            return;
        }
        TreeNode parent=null;
        TreeNode cur=root;
        TreeNode node=new TreeNode(key);
        while(cur!=null){
            if(cur.val<key){
                parent=cur;
                cur=cur.right;
            }else if (cur.val> key){
                parent=cur;
                cur=cur.left;
            }else {
                //在二叉搜索树中我们不能插入俩个相同的数据
                return;
            }
        }
        if(parent.val>key){
            parent.left=node;
        }else {
            parent.right=node;
        }
    }
    //查找的方法
    public TreeNode search(int val){
        TreeNode cur=root;
      while(cur!=null){
          if(cur.val<val){
              cur=cur.right;
          }else if(cur.val>val){
              cur=cur.left;
          }else {
              return cur;
          }
      }
      return null;
    }

    //二叉搜索树的删除（难点）
    public void remove(int key){
        TreeNode cur=root;
        TreeNode parent=null;
        if(cur.val<key){
            parent=cur;
            cur=cur.right;
        }else if(cur.val>key){
            parent=cur;
            cur=cur.left;
        }else {
            removeNode(parent,cur);
            return;
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            } else if (parent.left==cur) {
                parent.left=cur.right;
            }else {
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }else if(parent.left==cur){
                parent.left=cur.left;
            }else {
                parent.right=cur.left;
            }
        }else {           //左右两边都不是空的：找一个合适的数据提花val：1左树找最大值（左树最右边的结点）2右树找最小值（右树最左边的结点）
            TreeNode t=cur.right;
            TreeNode tp=cur;
            while(t.left!=null){
                tp=t;
                t=t.left;
            }
            cur.val=t.val;
            if(tp.left==t){
                tp.left=t.right;
            }else {
                tp.right=t.right;
            }


        }
    }


}
